define(window.backboneCommon.getViewDefine("creative.list"), function ($,require,Collection,tpl) {
    var defaultsOptions={
        campaignId:"",
        isRefreshSpread:true
    };
    var pagePrivate = {
        getDefaults :function () {
            return defaultsOptions
        },
        getOptions : function (options) {
            options=$.ExtCommon.isCheckEmpty(options)?{}:options;
            return $.ExtCommon.initMergeJson(this.getDefaults(),options);
        }
    };
    var backboneView= Backbone.View.extend({
        events: {},
        initialize: function () {
            this.modelAttach={};
            this.modelAttach.spread=this.model.get("modelSpread");
            this.listenTo(this.modelAttach.spread, "bind:AllList", this.bindSpread);
            this.listenTo(this.model, "bind:PageList", this.bindList);
            this.listenTo(this.model, "update:Status", this.updStatusCallback);
            this.render();
        },
        render:function(){
            var templateHtml=_.template(tpl);
            this.$el.html(templateHtml());
            return this;
        },
        initMain:function(options){
            this.elementModel={
                table:$("#tb_creativeList")
            };
            this.extObject={};
            this.pageData={initPage:false,initExtObject:{}};
            this.pageData.operateStatus=this.model.get("defOperateStatus");
            this.pageOptions=$.ExtCommon.initMergeJson(pagePrivate.getOptions(),options);
            $("#btn_addCreative").attr("href",$.ExtCommon.getStringConnect("#campaign/{0}/creative",[this.pageOptions.campaignId]));
            this._initInputSearch();
            this._initTimeRange();
        },
        initPage:function(param){
            var isChangeSpread=false;
            if(!$.ExtCommon.isCheckEmpty(param.spreadId)){
                var spreadId=param.spreadId.toString();
                if(this.extObject.spread){
                    isChangeSpread=spreadId!==this.extObject.spread.getValue();
                    this.extObject.spread.init(spreadId,false);
                }else{
                    isChangeSpread=true;
                    $("#search_creativeSpread").data("initValue",spreadId);
                }
            }
            var currentTime=this.getTimeRangeValue();
            var isChangeTime=param.startTime!==currentTime.startTime || param.endTime!==currentTime.endTime;
            if(isChangeTime){this.extObject.timeRange.setValue(param.startTime,param.endTime)}
            this.pageOptions= $.ExtCommon.initMergeJson(this.pageOptions,param);

            if(this.pageOptions.isRefreshSpread){
                this.collection.getSpreadList(this.pageOptions.campaignId);
            }
            if(!this.pageData.initPage){
                this.pageData.initPage=true;
                this._initPageList();
            }else{
                if(isChangeSpread||isChangeTime){this.refreshList()}
            }
        },
        _initInputSearch:function () {
            var self=this;
            self.extObject.inputSearch=$("#panel_inputSearch_creative").ExtInputSearch({
                placeholder:"创意ID,创意名称",
                searchCallback:function () {
                    self.refreshList();
                }
            })
        },

        _initTimeRange:function () {
            var self=this;
            self.extObject.timeRange=$("#search_creativeTimeRange").ExtDatePicker({type:"range",
                addQuick:{"本月": [$.ExtMoment.initMoment().startOf('month'), $.ExtMoment.initMoment()]},
                maxDate:$.ExtMoment.initMoment(),
                startValue:$.ExtMoment.initFormat(),endValue:$.ExtMoment.initFormat(),
                changeCallback: function () {self.refreshList()}
            });
        },
        getTimeRangeValue:function(){
            var arrTime =this.extObject.timeRange.getValue();
            return {startTime:arrTime[0],endTime:arrTime[1]}
        },

        bindSpread:function () {
            var self=this;
            var res=this.modelAttach.spread.get("dataAllList");
            if(self.extObject.spread){
                var value=self.extObject.spread.getValue();
                value=$.ExtCommon.isCheckEmpty(value)?-1:value;
                self.extObject.spread.replaceData(res.data,value,false);
            }else{
                self.extObject.spread=$("#search_creativeSpread").ExtSelect2({placeholder: "-推广计划-",allowClear: true,minimumResultsForSearch: 1,infoExt:{data:res.data,
                    initCallback:function(){self.pageData.initExtObject.spread=true},
                    changeCallback:function(){self.refreshList()}
                }});
            }
        },

        _initPageList: function () {
            var self=this;
            self.extObject.table=self.elementModel.table.ExtDataTable({
                columns: [
                    {data: "id", class: "w-60"},
                    {data: "name", class: ""},
                    {data: "statusName",class: "w-50 text-center"},
                    {data: "strategyCount", class: "w-60"},
                    {data: "pv",class: "w-85 text-right num-int"},
                    {data: "click",class: "w-85 text-right num-int"},
                    {data: "cr", class: "w-85 text-right num-float2"},
                    {data: "price", class: "w-85 text-right num-float2"},
                    {data: "cost",class: "w-110 text-right num-float2"}
                ],
                infoExt:{
                    ajaxDataPara:function(){
                        var param= {};
                        param.campaignId=self.pageOptions.campaignId;
                        var keyword = self.extObject.inputSearch.getValue();
                        if (!$.ExtCommon.isCheckEmpty(keyword)) {param.search = keyword;}
                        var spread ="";
                        if(self.pageData.initExtObject.spread){
                            spread = $("#search_creativeSpread").val();
                        }else{
                            if(!$.ExtCommon.isCheckEmpty(self.pageOptions.spreadId)){
                                spread = self.pageOptions.spreadId;
                            }
                        }
                        if (!$.ExtCommon.isCheckEmpty(spread)) {param.spread = spread;}
                        var timeRange=self.getTimeRangeValue();
                        param= $.ExtCommon.initMergeJson(param,timeRange);
                        return param;
                    },
                    ajaxWholeCallback:function(param){self.collection.getPageList(param)}
                },
                createdRow: function (row, data) {
                    data.campaignId=self.pageOptions.campaignId;
                    var elementTd=$("td", row);
                    elementTd.eq(1).html($.ExtCommon.getStringConnect('<a class="btn-operate longterm" href="#campaign/{0}/creative/{1}">{2}</a>',[data.campaignId,data.id,data.name]));
                    var tempJsonStatus = self._bindTableColumnByStatus(data.status);
                    elementTd.eq(2).html($.ExtCommon.getStringConnect(
                        '<a id="btn_creative_status_{0}" class="editable editable-click editable-init"  data-operate-type="status" href="javascript:">{1}</a>',
                        [data.id,data.statusName]
                    ));
                    elementTd.eq(2).find(".editable").data({list: tempJsonStatus.list});
                    elementTd.eq(3).html($.ExtCommon.getStringConnect('<span>{0}个策略</span>',[data.strategyCount]));
                },
                drawCallback: function () {
                    $.ExtNumeric.initAll();
                    self._initXEditable();
                    $.ExtAssist.urlParam.setUrl(self.elementModel.table.find("a"));
                }
            });
        },
        bindList:function(){
            var data=this.model.get("dataPageList");
            this.extObject.table.ajaxWholeRefreshData(data);
        },
        refreshList: function () {this.extObject.table.refresh()},

        _bindTableColumnByStatus: function (status) {
            status=$.ExtCommon.isCheckUndefined(status)?"":status.toString();
            var list=$.map(this.pageData.operateStatus,function (info) {
                if(info.showIds.indexOf(status)>-1){
                    return {value:info.id,text:info.name}
                }
            });
            return {status: status, list: list}
        },
        _initXEditable: function () {
            var self=this;
            self.elementModel.table.find(".editable-click.editable-init").each(function () {
                var _this = $(this);
                _this.removeClass("editable-init");
                var _thisData = _this.data();
                var tr = $(this).parents("tr:first");
                var row =self.extObject.table.getRowInfo(tr);
                var rowData=row.data();
                var operateType = _thisData["operateType"];
                switch(operateType){
                    case "status":
                        _this.ExtXEditable({
                            source: _thisData.list,
                            type: "select",
                            params: function (params) {
                                var newParams= {};
                                newParams.id=rowData.id;
                                newParams.campaignId=parseInt(self.pageOptions.campaignId);
                                newParams.status=parseInt($.trim(params.value));
                                return newParams;
                            },
                            infoExt:{
                                initControlOther: function () {
                                    _this.siblings(".editable-container").find("select").ExtSelect2({infoExt: {initValue: _thisData.list[0].value}});
                                },
                                ajaxWholeCallback:function (param) {
                                    $.ExtNotify.destroy();
                                    self.collection.updateStatus(param);
                                },
                                successCallback: function (res) {
                                    if(res.success){
                                        var tempJsonStatus = self._bindTableColumnByStatus(res.data.status);
                                        _this.text(res.data.statusName).data("list", tempJsonStatus.list);
                                        _this.ExtXEditable().refresh(tempJsonStatus.list);
                                        row.data().status = res.data.status;
                                        row.data().statusName = res.data.statusName;
                                    }
                                }
                            }
                        });
                        break;
                }
            });
        },
        updStatusCallback:function () {
            var result=this.model.get("dataUpdStatus");
            $("#btn_creative_status_"+result.req.id).ExtXEditable().ajaxWholeData(result.res);
        }
    });
    var viewModel=function(options){
        this.collection= new Collection();
        this.model=this.collection.model;
        this.view=new backboneView({el:options.pElement,collection:this.collection,model:this.model});
        this.view.initMain(options);
    };
    viewModel.prototype={
        init:function (param) {
            this.view.initPage(param);
        },
        getTimeValue:function () {
            return this.view.getTimeRangeValue();
        }
    };
    return viewModel;
});